﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Google.GData.Documents;
using Google.GData.Client;
using Google.GData.Extensions;
using Google.Documents;
using System.Threading;
using System.IO;
using System.Net;
using System.Web;
using FileHelpers;
using ResxLocalizationEditor.CommonPanel;

namespace ResxLocalizationEditor.GoogleImport {
    partial class GoogleDocsImport : WizardForm {

        public const string ApiAppKey = "Lck-ResxLocalizationEditor-1";

        public GoogleDocsImport() {
            InitializeComponent();

            //Hook onto primary panel
            panelLogin.AcceptButton.Click += new EventHandler(LoginPanel_Accept_click);

            //Folder panel
            _panelFolders = new FolderVisualizer();
            _panelFolders.ImportButton.Click += new EventHandler(FoldersPanel_Import_click);

            //Documents panel
            _panelDocuments = new DocumentsVisualizer();
            _panelDocuments.LoadButton.Click += new EventHandler(DocumentsPanel_Load_click);

            //Progress panel
            _panelImporting = new ImportingPanel();
        }

        string _username, _password;

        void LoginPanel_Accept_click(object sender, EventArgs e) {
            _username = panelLogin.Username;
            _password = panelLogin.Password;

            SwitchPanel(panelLogin, _panelFolders);
            _panelFolders.LoadFolders(_username, _password);
        }

        FolderVisualizer _panelFolders;
        DocumentsVisualizer _panelDocuments;
        ImportingPanel _panelImporting;

        void FoldersPanel_Import_click(object sender, EventArgs e) {
            Document selectedDocument = _panelFolders.SelectedDocument;
            if (selectedDocument == null)
                return;

            SwitchPanel(_panelFolders, _panelDocuments);
            _panelDocuments.LoadFolder(selectedDocument, _username, _password);
        }

        void DocumentsPanel_Load_click(object sender, EventArgs e) {
            var docs = _panelDocuments.SelectedDocuments.ToList();

            //GUI
            _panelImporting.ProgressBar.Maximum = docs.Count;
            _panelImporting.ProgressBar.Minimum = 0;
            _panelImporting.ProgressBar.Value = 0;
            SwitchPanel(_panelDocuments, _panelImporting);

            //Import resources
            ThreadPool.QueueUserWorkItem(DoImport, docs);
        }

        public ResourceSet ImportedResourceSet { get; private set; }

        delegate void GuiAction();

        private void DoImport(object objDocuments) {
            var documents = (IList<ImportableDocument>)objDocuments;
            ImportedResourceSet = new ResourceSet();

            var settings = new RequestSettings(ApiAppKey, _username, _password);
            var request = new DocumentsRequest(settings);

            for (int i = 0; i < documents.Count; ++i) {
                var doc = documents[i];

                BeginInvoke(new GuiAction(() => {
                    _panelImporting.ProgressBar.Value = i;
                }));

                var resource = FetchResource(request, doc);
                ImportedResourceSet.AddResource(resource);
            }

            Invoke(new GuiAction(() => {
                this.Close();
            }));
        }

        private Stream FetchSpreadsheet(DocumentsRequest request, Document doc) {
            return request.Download(doc, Document.DownloadType.csv);
        }

        private Resource FetchResource(DocumentsRequest request, ImportableDocument document) {
            var r = new Resource(document.Language);

            using (var stream = FetchSpreadsheet(request, document.Document)) {
                ImportedEntry[] imports;
                using (var reader = new StreamReader(stream)) {
                    var h = new FileHelpers.FileHelperEngine<ImportedEntry>();
                    imports = h.ReadStream(reader);
                }

                foreach(var import in imports){
                    if(!string.IsNullOrEmpty(import.Value))
                        r[import.Key] = import.Value;

                    if (!string.IsNullOrEmpty(import.Comment))
                        r.Comments[import.Key] = import.Comment;
                }

                return r;
            }
        }
    }
}
